package net.kaaass.poplan.util;

import java.util.ArrayList;
import java.util.List;

public class LocationUtil {
    private static int[] DEFAULT_ZOOM_TO_TILES_PER_EDGE = {1, 1, 1, 40, 40, 80, 80, 320, 1000, 2000, 2000, 4000, 8000, 16000, 16000, 32000};

    public static String toTileKeys(double lng, double lat, int zoom, int minLv, int maxLv) {
        return String.format("%d_%d_%d_%d_%d_100", zoom, lngToTile(lng, zoom), latToTile(lat, zoom), minLv, maxLv);
    }

    public static int lngToTile(double lng, int zoom) {
        return (int) Math.floor((lng + 180) / 360 * DEFAULT_ZOOM_TO_TILES_PER_EDGE[zoom]);
    }

    public static int latToTile(double lat, int zoom) {
        return (int) Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) +
                1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * DEFAULT_ZOOM_TO_TILES_PER_EDGE[zoom]);
    }

    public static double tileToLng(int x, int zoom) {
        return x / DEFAULT_ZOOM_TO_TILES_PER_EDGE[zoom] * 360 - 180;
    }

    public static double tileToLat(int y, int zoom) {
        double n = Math.PI - 2 * Math.PI * y / DEFAULT_ZOOM_TO_TILES_PER_EDGE[zoom];
        return 180 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));
    }

    /**
     * 生成两个坐标间的所有tileKeys
     *
     * @param lng1
     * @param lat1
     * @param lng2
     * @param lat2
     * @param minLv
     * @param maxLv
     * @param zoom
     * @return
     */
    public static String[] geneTileKeys(double lng1, double lat1, double lng2, double lat2, int minLv, int maxLv, int zoom) {
        List<String> tiles = new ArrayList<String>();
        int minTileX = lngToTile(lng1, zoom);
        int maxTileX = lngToTile(lng2, zoom);
        int minTileY = latToTile(lat1, zoom);
        int maxTileY = latToTile(lat2, zoom);
        for (int x = minTileX; x <= maxTileX; x++) {
            for (int y = minTileY; y <= maxTileY; y++) {
                tiles.add(String.format("%d_%d_%d_%d_%d_100", zoom, x, y, minLv, maxLv));
            }
        }
        return tiles.toArray(new String[0]);
    }

    public static String[] geneTileKeys(double lng1, double lat1, double lng2, double lat2, int minLv, int maxLv) {
        return geneTileKeys(lng1, lat1, lng2, lat2, minLv, maxLv, 15);
    }
}
